/**
 * 时间管理相关Mock数据
 */

import { generateId, randomNumber, randomChoice, randomDate, formatDate, paginate } from '../utils'
import { TIME_CONFIG } from '@/config'

// 模拟时间记录数据
const mockTimeRecords = []

// 模拟活动分类数据
const mockActivityCategories = TIME_CONFIG.ACTIVITY_CATEGORIES.map(category => ({
  id: generateId(),
  ...category,
  isCustom: false,
  createdAt: '2024-01-01T00:00:00.000Z',
  updatedAt: '2024-01-01T00:00:00.000Z'
}))

// 模拟计时器数据
const mockTimers = []

// 生成模拟时间记录
function generateTimeRecords() {
  for (let i = 0; i < 80; i++) {
    const category = randomChoice(mockActivityCategories)
    const startDate = randomDate(new Date(2024, 0, 1), new Date())
    const duration = randomNumber(15, 240) // 15分钟到4小时
    const endDate = new Date(startDate.getTime() + duration * 60 * 1000)
    
    mockTimeRecords.push({
      id: generateId(),
      categoryId: category.id,
      categoryName: category.name,
      title: generateActivityTitle(category.id),
      description: randomChoice(['', '专注工作', '效率很高', '有点分心', '状态不错'], 1),
      startTime: startDate.toISOString(),
      endTime: endDate.toISOString(),
      duration, // 分钟
      tags: randomChoice(['重要', '紧急', '学习', '工作', '娱乐'], randomNumber(0, 2)),
      location: randomChoice(['办公室', '家里', '咖啡厅', '图书馆', ''], 1),
      mood: randomChoice(['excellent', 'good', 'normal', 'bad'], 1),
      productivity: randomNumber(1, 5),
      createdAt: startDate.toISOString(),
      updatedAt: startDate.toISOString()
    })
  }
  
  // 按开始时间倒序排列
  mockTimeRecords.sort((a, b) => new Date(b.startTime) - new Date(a.startTime))
}

// 生成活动标题
function generateActivityTitle(categoryId) {
  const titles = {
    work: ['项目开发', '会议讨论', '文档编写', '代码审查', '需求分析'],
    study: ['阅读书籍', '在线课程', '技能学习', '知识整理', '考试准备'],
    exercise: ['跑步', '健身', '瑜伽', '游泳', '骑行'],
    entertainment: ['看电影', '听音乐', '游戏', '社交', '购物'],
    social: ['朋友聚会', '家庭时间', '电话沟通', '聚餐', '活动参与'],
    rest: ['午休', '放松', '冥想', '散步', '发呆'],
    other: ['其他活动', '杂事处理', '临时任务', '突发事件', '未分类']
  }
  
  const categoryTitles = titles[categoryId] || titles.other
  return randomChoice(categoryTitles)
}

// 初始化时间记录
generateTimeRecords()

export default {
  // 获取时间记录
  'GET /time/records': async (params = {}) => {
    const { page = 1, pageSize = 20, categoryId, startDate, endDate, tags } = params
    
    let filteredRecords = [...mockTimeRecords]
    
    // 按分类筛选
    if (categoryId) {
      filteredRecords = filteredRecords.filter(record => record.categoryId === categoryId)
    }
    
    // 按日期筛选
    if (startDate) {
      filteredRecords = filteredRecords.filter(record => 
        formatDate(new Date(record.startTime), 'YYYY-MM-DD') >= startDate
      )
    }
    if (endDate) {
      filteredRecords = filteredRecords.filter(record => 
        formatDate(new Date(record.startTime), 'YYYY-MM-DD') <= endDate
      )
    }
    
    // 按标签筛选
    if (tags && tags.length > 0) {
      filteredRecords = filteredRecords.filter(record => 
        tags.some(tag => record.tags.includes(tag))
      )
    }
    
    return paginate(filteredRecords, page, pageSize)
  },
  
  // 创建时间记录
  'POST /time/records': async (data) => {
    const { categoryId, title, description, startTime, endTime, tags, location, mood, productivity } = data
    
    // 验证必填字段
    if (!categoryId || !title || !startTime || !endTime) {
      throw new Error(JSON.stringify({ code: 1001, message: '分类、标题、开始时间和结束时间不能为空' }))
    }
    
    // 验证时间
    const start = new Date(startTime)
    const end = new Date(endTime)
    if (start >= end) {
      throw new Error(JSON.stringify({ code: 1001, message: '结束时间必须晚于开始时间' }))
    }
    
    // 验证分类是否存在
    const category = mockActivityCategories.find(cat => cat.id === categoryId)
    if (!category) {
      throw new Error(JSON.stringify({ code: 1003, message: '活动分类不存在' }))
    }
    
    const duration = Math.round((end.getTime() - start.getTime()) / (1000 * 60)) // 分钟
    
    const newRecord = {
      id: generateId(),
      categoryId,
      categoryName: category.name,
      title,
      description: description || '',
      startTime: start.toISOString(),
      endTime: end.toISOString(),
      duration,
      tags: tags || [],
      location: location || '',
      mood: mood || 'normal',
      productivity: productivity || 3,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockTimeRecords.unshift(newRecord)
    
    return newRecord
  },
  
  // 更新时间记录
  'PUT /time/records/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const recordIndex = mockTimeRecords.findIndex(record => record.id === id)
    
    if (recordIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '时间记录不存在' }))
    }
    
    const allowedFields = ['categoryId', 'title', 'description', 'startTime', 'endTime', 'tags', 'location', 'mood', 'productivity']
    const updates = {}
    
    allowedFields.forEach(field => {
      if (data[field] !== undefined) {
        updates[field] = data[field]
      }
    })
    
    // 如果更新了分类，需要更新分类名称
    if (updates.categoryId) {
      const category = mockActivityCategories.find(cat => cat.id === updates.categoryId)
      if (!category) {
        throw new Error(JSON.stringify({ code: 1003, message: '活动分类不存在' }))
      }
      updates.categoryName = category.name
    }
    
    // 如果更新了时间，需要重新计算持续时间
    if (updates.startTime || updates.endTime) {
      const oldRecord = mockTimeRecords[recordIndex]
      const startTime = updates.startTime ? new Date(updates.startTime) : new Date(oldRecord.startTime)
      const endTime = updates.endTime ? new Date(updates.endTime) : new Date(oldRecord.endTime)
      
      if (startTime >= endTime) {
        throw new Error(JSON.stringify({ code: 1001, message: '结束时间必须晚于开始时间' }))
      }
      
      updates.duration = Math.round((endTime.getTime() - startTime.getTime()) / (1000 * 60))
    }
    
    mockTimeRecords[recordIndex] = {
      ...mockTimeRecords[recordIndex],
      ...updates,
      updatedAt: new Date().toISOString()
    }
    
    return mockTimeRecords[recordIndex]
  },
  
  // 删除时间记录
  'DELETE /time/records/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const recordIndex = mockTimeRecords.findIndex(record => record.id === id)
    
    if (recordIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '时间记录不存在' }))
    }
    
    mockTimeRecords.splice(recordIndex, 1)
    
    return { message: '删除成功' }
  },
  
  // 开始计时
  'POST /time/timer/start': async (data) => {
    const { categoryId, title, description } = data
    
    // 验证必填字段
    if (!categoryId || !title) {
      throw new Error(JSON.stringify({ code: 1001, message: '分类和标题不能为空' }))
    }
    
    // 验证分类是否存在
    const category = mockActivityCategories.find(cat => cat.id === categoryId)
    if (!category) {
      throw new Error(JSON.stringify({ code: 1003, message: '活动分类不存在' }))
    }
    
    // 检查是否已有正在运行的计时器
    const runningTimer = mockTimers.find(timer => timer.status === 'running')
    if (runningTimer) {
      throw new Error(JSON.stringify({ code: 1004, message: '已有正在运行的计时器，请先停止' }))
    }
    
    const newTimer = {
      id: generateId(),
      categoryId,
      categoryName: category.name,
      title,
      description: description || '',
      startTime: new Date().toISOString(),
      pausedDuration: 0, // 暂停的总时长（毫秒）
      status: 'running', // running, paused, stopped
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockTimers.push(newTimer)
    
    return newTimer
  },
  
  // 停止计时
  'POST /time/timer/stop/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const timerIndex = mockTimers.findIndex(timer => timer.id === id)
    
    if (timerIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '计时器不存在' }))
    }
    
    const timer = mockTimers[timerIndex]
    if (timer.status === 'stopped') {
      throw new Error(JSON.stringify({ code: 1001, message: '计时器已停止' }))
    }
    
    const endTime = new Date()
    const startTime = new Date(timer.startTime)
    const totalDuration = Math.round((endTime.getTime() - startTime.getTime() - timer.pausedDuration) / (1000 * 60))
    
    // 创建时间记录
    const timeRecord = {
      id: generateId(),
      categoryId: timer.categoryId,
      categoryName: timer.categoryName,
      title: timer.title,
      description: timer.description,
      startTime: timer.startTime,
      endTime: endTime.toISOString(),
      duration: totalDuration,
      tags: [],
      location: '',
      mood: 'normal',
      productivity: 3,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockTimeRecords.unshift(timeRecord)
    
    // 更新计时器状态
    mockTimers[timerIndex] = {
      ...timer,
      endTime: endTime.toISOString(),
      duration: totalDuration,
      status: 'stopped',
      updatedAt: new Date().toISOString()
    }
    
    return {
      timer: mockTimers[timerIndex],
      timeRecord
    }
  },
  
  // 暂停计时
  'POST /time/timer/pause/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const timerIndex = mockTimers.findIndex(timer => timer.id === id)
    
    if (timerIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '计时器不存在' }))
    }
    
    const timer = mockTimers[timerIndex]
    if (timer.status !== 'running') {
      throw new Error(JSON.stringify({ code: 1001, message: '计时器未在运行' }))
    }
    
    mockTimers[timerIndex] = {
      ...timer,
      status: 'paused',
      pausedAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    return mockTimers[timerIndex]
  },
  
  // 恢复计时
  'POST /time/timer/resume/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const timerIndex = mockTimers.findIndex(timer => timer.id === id)
    
    if (timerIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '计时器不存在' }))
    }
    
    const timer = mockTimers[timerIndex]
    if (timer.status !== 'paused') {
      throw new Error(JSON.stringify({ code: 1001, message: '计时器未暂停' }))
    }
    
    // 计算暂停时长
    const pausedDuration = new Date().getTime() - new Date(timer.pausedAt).getTime()
    
    mockTimers[timerIndex] = {
      ...timer,
      status: 'running',
      pausedDuration: timer.pausedDuration + pausedDuration,
      pausedAt: undefined,
      updatedAt: new Date().toISOString()
    }
    
    return mockTimers[timerIndex]
  },
  
  // 获取活动分类
  'GET /time/activity-categories': async () => {
    return mockActivityCategories
  },
  
  // 创建活动分类
  'POST /time/activity-categories': async (data) => {
    const { name, icon, color } = data
    
    // 验证必填字段
    if (!name) {
      throw new Error(JSON.stringify({ code: 1001, message: '分类名称不能为空' }))
    }
    
    // 检查名称是否已存在
    if (mockActivityCategories.find(category => category.name === name)) {
      throw new Error(JSON.stringify({ code: 1004, message: '分类名称已存在' }))
    }
    
    const newCategory = {
      id: generateId(),
      name,
      icon: icon || 'more-horizontal',
      color: color || '#34495e',
      isCustom: true,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockActivityCategories.push(newCategory)
    
    return newCategory
  },
  
  // 更新活动分类
  'PUT /time/activity-categories/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const categoryIndex = mockActivityCategories.findIndex(category => category.id === id)
    
    if (categoryIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '活动分类不存在' }))
    }
    
    const category = mockActivityCategories[categoryIndex]
    if (!category.isCustom) {
      throw new Error(JSON.stringify({ code: 1002, message: '系统分类不允许修改' }))
    }
    
    const allowedFields = ['name', 'icon', 'color']
    const updates = {}
    
    allowedFields.forEach(field => {
      if (data[field] !== undefined) {
        updates[field] = data[field]
      }
    })
    
    // 检查名称重复（排除自己）
    if (updates.name && mockActivityCategories.find(cat => cat.name === updates.name && cat.id !== id)) {
      throw new Error(JSON.stringify({ code: 1004, message: '分类名称已存在' }))
    }
    
    mockActivityCategories[categoryIndex] = {
      ...category,
      ...updates,
      updatedAt: new Date().toISOString()
    }
    
    return mockActivityCategories[categoryIndex]
  },
  
  // 删除活动分类
  'DELETE /time/activity-categories/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const categoryIndex = mockActivityCategories.findIndex(category => category.id === id)
    
    if (categoryIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '活动分类不存在' }))
    }
    
    const category = mockActivityCategories[categoryIndex]
    if (!category.isCustom) {
      throw new Error(JSON.stringify({ code: 1002, message: '系统分类不允许删除' }))
    }
    
    // 检查是否有关联的时间记录
    const hasRecords = mockTimeRecords.some(record => record.categoryId === id)
    if (hasRecords) {
      throw new Error(JSON.stringify({ code: 1004, message: '该分类存在时间记录，无法删除' }))
    }
    
    mockActivityCategories.splice(categoryIndex, 1)
    
    return { message: '删除成功' }
  },
  
  // 获取时间统计
  'GET /time/stats': async (params = {}) => {
    const { period = 'week' } = params
    
    const now = new Date()
    let startDate, endDate
    
    switch (period) {
      case 'day':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
        endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
        break
      case 'week':
        const weekStart = now.getDate() - now.getDay()
        startDate = new Date(now.getFullYear(), now.getMonth(), weekStart)
        endDate = new Date(now.getFullYear(), now.getMonth(), weekStart + 7)
        break
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1)
        break
      default:
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
        endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
    }
    
    const periodRecords = mockTimeRecords.filter(record => {
      const recordDate = new Date(record.startTime)
      return recordDate >= startDate && recordDate < endDate
    })
    
    // 按分类统计
    const categoryStats = {}
    periodRecords.forEach(record => {
      if (!categoryStats[record.categoryId]) {
        categoryStats[record.categoryId] = {
          categoryId: record.categoryId,
          categoryName: record.categoryName,
          totalDuration: 0,
          recordCount: 0
        }
      }
      categoryStats[record.categoryId].totalDuration += record.duration
      categoryStats[record.categoryId].recordCount += 1
    })
    
    const totalDuration = periodRecords.reduce((sum, record) => sum + record.duration, 0)
    const averageProductivity = periodRecords.length > 0 ? 
      (periodRecords.reduce((sum, record) => sum + record.productivity, 0) / periodRecords.length).toFixed(1) : 0
    
    return {
      period,
      totalDuration,
      recordCount: periodRecords.length,
      averageProductivity: parseFloat(averageProductivity),
      categoryStats: Object.values(categoryStats),
      dailyAverage: period === 'week' ? Math.round(totalDuration / 7) : 
                   period === 'month' ? Math.round(totalDuration / 30) : totalDuration
    }
  },
  
  // 获取时间分布分析
  'GET /time/analysis/distribution': async (params = {}) => {
    const { period = 'week' } = params
    
    // 按小时分布统计
    const hourlyDistribution = Array(24).fill(0)
    mockTimeRecords.forEach(record => {
      const hour = new Date(record.startTime).getHours()
      hourlyDistribution[hour] += record.duration
    })
    
    // 按分类分布统计
    const categoryDistribution = {}
    mockTimeRecords.forEach(record => {
      if (!categoryDistribution[record.categoryName]) {
        categoryDistribution[record.categoryName] = 0
      }
      categoryDistribution[record.categoryName] += record.duration
    })
    
    return {
      hourlyDistribution: hourlyDistribution.map((duration, hour) => ({
        hour,
        duration
      })),
      categoryDistribution: Object.entries(categoryDistribution).map(([name, duration]) => ({
        name,
        duration
      }))
    }
  }
}